package es.ats.codington.web.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import es.ats.codington.festival.domain.Visitor;
import es.ats.codington.festival.services.VisitorService;

/**
 * Servlet implementation class editUserServlet
 */
@WebServlet("/editUserServlet")
public class editUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public editUserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String userName=null;
		Cookie loginCookie=null;
		Cookie[] cookies = request.getCookies();
		if (cookies != null){
			for(Cookie cookie : cookies){
				if(cookie.getName().equals("user")){
					userName=cookie.getValue();
					break;
				}
			}
		}
		if(userName ==null){
			response.sendRedirect("login.jsp");
		}
		VisitorService visitorS=new VisitorService();
		
		response.setContentType("text/html");
		PrintWriter out=response.getWriter();
		
		String fname=request.getParameter("nombre");
		String lname=request.getParameter("apell");
		String email=request.getParameter("email");
		String dni=request.getParameter("dni");
		String nphone=request.getParameter("phone");
		String address=request.getParameter("adress");
		String pass="cas";
		
		Visitor visitor=new Visitor(fname,lname,userName,email,dni,nphone,address,pass, false);
				int i=visitorS.updateVisitorSevice(visitor, userName);
		
		if(i==1){
			RequestDispatcher rd= request.getRequestDispatcher("index2.jsp");
			rd.forward(request, response);
		}
		else {
			out.print("Don't edit this user.");
			RequestDispatcher rd= request.getRequestDispatcher("editUser.jsp");
			rd.include(request, response);
		}
	out.close();
	}

}
